package org.yxs.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: y-xs
 * @date: 2021/08/25 18:35
 * @description: 索引操作
 */
public class ElasticsearchIndexTest {

    /**
     * 连接客户端
     */
    private RestHighLevelClient client;

    @Before
    public void init() {
        HttpHost serverHost = new HttpHost("127.0.0.1", 9200);
        client = new RestHighLevelClient(RestClient.builder(serverHost));
    }

    @After
    public void destroy() {
        if (Objects.nonNull(client)) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建索引：有则报错，无则新建
     */
    @Test
    public void testCreate() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("java");
        CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 查询索引信息
     */
    @Test
    public void testQuery() throws IOException {
        GetIndexRequest request = new GetIndexRequest("java");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        // 获取别名
        System.out.println(response.getAliases());
//        PrintUtil.buttyPrint(response.getAliases(), "getAliases");
        // 获取默认设置
        System.out.println(response.getDefaultSettings());
//        PrintUtil.buttyPrint(response.getDefaultSettings(), "getDefaultSettings");
        // 获取索引信息
        System.out.println(response.getIndices());
//        PrintUtil.buttyPrint(response.getIndices(), "getIndices");
        // 获取映射信息
        System.out.println(response.getMappings());
//        PrintUtil.buttyPrint(response.getMappings(), "getMappings");
    }

    /**
     * 删除索引
     */
    @Test
    public void testDelete() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("java");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

}
